package main

import (
	"bufio"
	"fmt"
	"gogame/game/manage/model"
	"gogame/lib"
	"gogame/lib/database/mongo"
	"gogame/logger"
	"os"
)

// WriteModelLogByFile 超时重试的日志入库
func WriteModelLogByFile() {
	mongo.InitMongo()

	_folderPath := lib.GetFilePath("file_mongo_log")
	_fileNameList := lib.ScanDir(_folderPath)
	// 没有需要处理的log
	if _fileNameList == nil || len(_fileNameList) == 0 {
		return
	}

	for _, _fileName := range _fileNameList {
		_filePath := fmt.Sprintf("%s/%s", _folderPath, _fileName)

		// 处理文件内modelLog
		HandleModelLogFile(_filePath)

		// 删除文件
		lib.DelFile(_filePath)
	}

}

// HandleModelLogFile modelLog文件处理
func HandleModelLogFile(filePath string) {
	_file, err := lib.OpenFile(filePath, os.O_RDONLY)
	if err != nil {
		return
	}
	defer _file.Close()

	// 处理log
	var modelLogList []any
	buf := bufio.NewScanner(_file)
	for buf.Scan() {
		_fileData := buf.Bytes()
		var modelLog *model.ModelLog
		lib.Loads(_fileData, &modelLog)
		if modelLog == nil {
			logger.Print("WriteMongoLogByFile logList.Len == 0\n_fileData --> %s", _fileData)
			continue
		}
		modelLogList = append(modelLogList, modelLog)
	}

	// 插入model_log
	if len(modelLogList) > 0 {
		_, err := mongo.Mdb.InsertMany("model_log", modelLogList)
		if err != nil {
			logger.Print("WriteMongoLogByFile InsertMany fail!\nerr --> %s", err.Error())
		}
	}

}

func main() {
	WriteModelLogByFile()
}
